// app.js
const path = require('path')

const Koa = require('koa');
const Router = require('koa-router');
// const bodyParser = require('koa-bodyparser');
const { koaBody } = require('koa-body');
// 静态资源映射模块 
const KoaStatic = require('koa-static')

const sequelize = require('./database');
const userRoutes = require('./routes/userRoutes');
const courseRoutes = require('./routes/courseRoutes');
const transactionRoutes = require('./routes/transactionRoutes');
const videoRoutes = require('./routes/videoRoutes');
const logRoutes = require('./routes/logRoutes');
const uploadRoutes = require('./routes/uploadRoutes');
const paymentRoutes = require('./routes/paymentRoutes')

const User = require('./models/User');
const Course = require('./models/Course');
const Transaction = require('./models/Transaction');
const Video = require('./models/Video');
const Log = require('./models/Log');
const Files = require('./models/Files');
const Payment = require('./models/Payment')


const app = new Koa();
const router = new Router();

// // 数据库连接测试
sequelize
  .authenticate()
  .then(() => {
    console.log('连接数据库成功~');
    // createTables()
  })
  .catch((error) => {
    console.log('连接数据库失败', error);
  });

// 中间件
// app.use(bodyParser());

app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: path.join(__dirname, 'uploads'), // 设置文件上传的目录
    keepExtensions: true, // 保留文件扩展名
  },
}));
// 映射静态资源
app.use(KoaStatic(process.cwd() + '/uploads'))


// 路由
router.use('/users', userRoutes.routes());
router.use('/courses', courseRoutes.routes());
router.use('/transactions', transactionRoutes.routes());
router.use('/videos', videoRoutes.routes());
router.use('/logs', logRoutes.routes());
router.use('/payment', paymentRoutes.routes())

// 添加路由中间件
app.use(router.routes());
app.use(router.allowedMethods());
app.use(uploadRoutes.routes());


// 创建数据表
async function createTables() {
  try {
    await User.sync();
    await Course.sync();
    await Transaction.sync();
    await Video.sync();
    await Log.sync();
    await Files.sync();
    await Payment.sync();

    console.log('全部创建完成~');
  } catch (error) {
    console.error('创建数据表失败:', error);
  }
}

// createTables();

// 启动服务器
app.listen(3000, () => {
  console.log('http://localhost:3000');
});
